package com.lenovo.spider.common;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import reactor.core.publisher.Mono;
import reactor.core.publisher.MonoSink;
import reactor.core.scheduler.Schedulers;

import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 * @author <a href="mailto:liuhan3@lenovo.com">HanL(liuhan3)</a>
 * on 2018/3/21 16:38
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Functions {

    /**
     * 将一个同步的方法，使用Mono包装成异步的
     *
     * @param fn  同步方法
     * @param <T>
     * @return
     */
    public static <T> Function<T, Mono<T>> monoWrap(Function<T, T> fn) {
        return task -> Mono.create((MonoSink<T> sink) -> sink.success(fn.apply(task))).subscribeOn(Schedulers.elastic());
    }

    /**
     * 函数版的三元表达式，如果predicate.test 为true, 返回trueConsumer； 反之，返回falseConsumer
     *
     * @param predicate
     * @param trueConsumer
     * @param falseConsumer
     * @return
     */
    public static <T> Consumer<T> when(Predicate<T> predicate, Consumer<T> trueConsumer, Consumer<T> falseConsumer) {
        return task -> (predicate.test(task) ? trueConsumer : falseConsumer).accept(task);
    }


}
